package cn.donting.jme.edit.attribute;

import cn.donting.fx.ui.NumberField;
import com.jme3.math.Vector3f;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;

import java.net.URL;
import java.util.ResourceBundle;

public class Vector3fAttribute extends Attribute<Vector3f> implements Initializable,ChangeListener<Number> {

    private Node node;

    @FXML
    public NumberField x;
    @FXML
    public NumberField y;
    @FXML
    public NumberField z;

    private Vector3fAttribute() {

    }

    public static Vector3fAttribute getInstance() {
        FXMLLoader load = new FXMLLoader(Vector3fAttribute.class.getClassLoader().getResource("cn/donting/jme/edit/attribute/Vector3fAttribute.fxml"));
        try {
            load.setControllerFactory(aClass -> new Vector3fAttribute());
            Node node = load.load();
            Vector3fAttribute controller = load.getController();
            controller.node = node;
            return controller;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
       //添加监听器
        x.floatProperty.addListener(this::changed);
        y.floatProperty.addListener(this::changed);
        z.floatProperty.addListener(this::changed);
    }

    @Override
    public void setValue(Vector3f value) {
        x.setValue(value.x);
        y.setValue(value.y);
        z.setValue(value.z);
    }

    private void setSuperValue(Vector3f value) {
        super.setValue(value);
    }

    @Override
    public Node getUINode() {
        return node;
    }

    @Override
    public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        setSuperValue(new Vector3f(x.getFloat(), y.getFloat(),z.getFloat()));
    }
}
